import Axios from 'axios'
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import { useRouter } from 'vue-router';
import router from '@/router';

const axios = Axios.create({
  // baseURL: 'http://localhost:7070',
  baseURL: '/adminApi',
  timeout: 20000//超时时间20s
})
//允许浏览器发送请求的时候携带cookie
axios.defaults.withCredentials = true


//request拦截器
//可以在请求发送前对请求做一些处理
//比如统一加token,对请求参数统一加密

// let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
axios.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json;charset=utf-8';

  //从cookie中获取jwt令牌
  const token = Cookies.get('adminToken')

  //判断令牌是否存在,将其添加到请求头中
  // if(token){
  //   config.headers['token'] = token
  // }

  return config
}, error => {
  ElMessage.error("未登录账号，请登录")
  window.location.href = '/login'
  return Promise.reject(error)
});

//response拦截器
//可以在接口响应后统一处理结果
axios.interceptors.response.use(
  response => {
    let res = response.data;
    //当权限验证不通过的时候给出提示
    if (res.code == 401) {
      setTimeout(() => {
        router.push("/login")
      }, 1000)
    }
    return response;
  },
  error => {
    let res = error.response.data
    ElMessage.error(error.response.data.info)
    if (res.code == 401) {
      setTimeout(() => {
        router.push("/login")
      }, 1000)
    }
    console.log('err' + error)
    return Promise.reject(error)
  }
)

export default axios
